import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    auth: false,
    selfInfo: null,
    userCache: [],
  },
  mutations: {
    auth: function (state) {
      state.auth = true;
    },
    selfInfo: function (state, userInfo) {
      state.selfInfo = userInfo;
    },
    initUserCache: function (state, size) {
      state.userCache = [];
      state.userCache.length = size;
    },
    saveUsers: function (state, data) {
      const users = data.users;
      const begin = data.begin;
      const num = data.num;
      for (let i = 0; i < num && begin + i < state.userCache.length; i++)
        state.userCache[begin + i] = users[i];
    },
    invalidUsers: function (state, data) {
      const begin = data.begin;
      const num = data.num;
      if (!begin || !num)
        this.initUserCache(state, state.userCache.length);
      else
        for (let i = 0; i < num && begin + i < state.userCache.length; i++)
          state.userCache[begin + i] = undefined;
    },
    removeUsers: function (state, data) {
      const begin = data.begin;
      const num = data.num;
      if (!begin || !num)
        this.initUserCache(state, 0);
      else
        state.userCache.splice(begin, num);
    },
  },
  getters: {
    users: state => (index, size) => {
      return state.userCache.slice(index * size, index * size + size)
    }
  },
  actions: {
    selfInfo: function (ctx) {
      axios.get("api/user/get")
        .then(res => {
          const code = res.data.statusCode;
          if (code === 200)
            ctx.commit("selfInfo", res.data.responseData);
        })
    }
  }
});

export default store;
